﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using CeskyRozhlasRT.DataModel;

namespace CeskyRozhlasRT.Parsing
{
    public class StationListWebRetrieverAsync : StationsRetriever, IStationListRetriever
    {

        public async Task ParseXmlStationsList(XmlReader iReader)
        {
            //XML parsing might be very time consuming, so let's do every station in separate worker thread.
            var aStationNodes = new List<Task<StationInfo>>();
            while (iReader.Read())
            {
                switch (iReader.NodeType)
                {
                    case XmlNodeType.Element:
                        if (iReader.Name == "station")
                        {
                            aStationNodes.Add(parseXmlStationDescriptionAsync(iReader.ReadOuterXmlAsync()));
                        }
                        break;
                }
            }

            foreach (var aTask in aStationNodes)
            {
                MStationsList.Add(await aTask);
            }
        }

        //Async wrapper for the sake of testing
        public async Task<StationInfo> parseXmlStationDescriptionAsync(Task<String> iXmlRepresentation)
        {
            return StationXmlParser.ParseStationDescription(await iXmlRepresentation);
        }
    }
}
